const { error } = require("console");
var express = require("express");
var router = express.Router();
const fs = require("fs");
const path = require("path");

/* GET users listing. */
router.post("/", function (req, res, next) {
  const userid = req.body.userid || "";
  const username = req.body.username || "";
  const password = req.body.password || "";
  const response = {
    username: username,
    userid: userid,
    message: "",
    success: false,
  };

  if (userid === "") {
    response.success = false;
    response.message = "请输入工号";
    res.send(JSON.stringify(response));
    return;
  }
  if (username === "") {
    response.success = false;
    response.message = "请输入用户名";
    res.send(JSON.stringify(response));
    return;
  }
  if (password === "") {
    response.success = false;
    response.message = "请输入密码";
    res.send(JSON.stringify(response));
    return;
  }

  try {
    let data = fs.readFileSync(
      path.resolve(__dirname, "../data/data.json"),
      "utf8"
    );
    data = JSON.parse(data);
    const userInfo = data.users.find((item) => item.userid === userid);
    if (userInfo) {
      response.username = userInfo.username || "";
      response.userid = userInfo.userid || "";
      response.message = "已有账号，请登录";
      response.success = false;
      res.send(JSON.stringify(response));
    } else {
      data.users.push({
        userid: userid,
        username: username,
        password: password,
      });
      // 没有用户才注册
      fs.writeFileSync(
        path.resolve(__dirname, "../data/data.json"),
        JSON.stringify(data),
        {
          encoding: "utf8",
        }
      );
      response.success = true;
      response.message = "注册成功，请登录";
      res.send(JSON.stringify(response));
    }
  } catch (err) {
    console.error(`Got an error trying to read the file: ${err.message}`);
    res.send("error", error);
  }
});

module.exports = router;
